package mobi.bantu.web;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import mobi.bantu.bean.Contact;
import mobi.bantu.bean.Page;
import mobi.bantu.bean.Result;
import mobi.bantu.bean.SearchParam;
import mobi.bantu.service.ContactService;

@Controller
@RequestMapping("contact")
public class ContactController {

    @Resource
    private ContactService contactService;

    @RequestMapping("list")
    public String list() {
        return "contact/list";
    }

    @RequestMapping("list-data")
    @ResponseBody
    public Page<Contact> listData(SearchParam sp) {
        return Page.create(contactService.list(sp.getSp()), contactService.count(sp.getSp()));
    }

    @RequestMapping("delete")
    @ResponseBody
    public Result delete(Long id) {
        contactService.delete(id);
        return Result.success();
    }

    @RequestMapping("form")
    public String form(Long id, Model model) {
        if (id == null) return "contact/form";
        model.addAttribute("info", contactService.get(id));
        return "contact/update";
    }

    @RequestMapping("update")
    @ResponseBody
    public Result update(Contact contract) {
        try {
            contactService.update(contract);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.byMsg(e.getMessage());
        }
    }

    @RequestMapping("add")
    @ResponseBody
    public Result add(Contact contact) {
        try {
            contactService.save(contact);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.byMsg(e.getMessage());
        }
    }
}
